import { useEffect, useState } from 'react';
import { Button, Checkbox, Form, Input, Select, notification } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import styles from './index.module.scss';
import { useDispatch, useSelector } from 'react-redux'
import { setUserInfo } from '@/reducers/main';
import { login } from '@/service'
import Cookies from "js-cookie";
import { useTranslation } from 'react-i18next';
const FormItem = Form.Item;
const Option = Select.Option;
import { useWebSocket } from '@/WebSocketContext';

import ForgetPwd from './ForgetPwd';

export default props => {
    const [form] = Form.useForm();
    const { t, i18n } = useTranslation();
    const [notificationApi, contextHolder] = notification.useNotification();
    const { connectWebSocket } = useWebSocket();
    const initState = () => ({
        userName: '',
        password: '',
        // remember: false,
        loading: false,
        pwdOpen: false,
    });
    const [state, setState] = useState(initState);
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const [selectedLang, setDefaultlagValue] = useState('en');

    useEffect(() => {
        const userinfo = localStorage.getItem('userinfo'),
            userToken = Cookies.get('token');
        if (userToken) {
            navigate('/login');
        }
    }, [form]);
    const handleLanguageChange = (value) => {
        i18n.changeLanguage(value);
        localStorage.setItem('language', value);  // 持久化语言选择
        setDefaultlagValue(value);
    };
    useEffect(() => {
        const savedLanguage = localStorage.getItem('language') || 'en';
        setDefaultlagValue(savedLanguage);
        i18n.changeLanguage(savedLanguage);
    }, [i18n]);
    const onSubmit = async () => {
        try {
            const values = await form.validateFields();
            const { userName, password } = values;
            const params = {
                username: userName,
                password: password
            };
            setState((prevState) => ({ ...prevState, loading: true }));
            const res = await login(params);
            const { expire, token, user, code, msg } = res || {};
            if (code === 0) {
                Cookies.set('token', token, { expires: expire });
                connectWebSocket(token);
                dispatch(setUserInfo(user));
                localStorage.setItem("userinfo", JSON.stringify(user));
                navigate('/');
            } else {
                notificationApi.error({
                    message: 'Login Failed',
                    description: msg,
                });
            }
        } catch (error) {
            if (error.msg) {
                notificationApi.error({
                    message: 'Login Failed',
                    description: error.msg,
                });
            }
        } finally {
            setState((prevState) => ({ ...prevState, loading: false }));
        }
    };
    return (
        <div className={styles['container']}>
            <div className={styles.logo}>
                <img src="/images/logo.svg" alt="" />
                <div>
                    <Select value={selectedLang}
                        style={{ width: '100px' }} onChange={handleLanguageChange}>
                        <Option value="en">English</Option>
                        <Option value="zh_CN">中文</Option>
                        {/* <Option value="ja">日本語</Option> */}
                    </Select>
                </div>
            </div>
            <div className={styles.item}>
                <div className={styles.left}>
                    <div>{t('login.leftTextTwo')}</div>
                    <div>{t('login.leftTextOne')}</div>
                    <img src="/images/loginBg.svg" alt="" />
                </div>
                <div className={styles.right}>
                    <div className={styles.title}>{t('login.welcome')}</div>
                    <Form
                        form={form}
                        style={{ width: 340, margin: '0 auto' }}
                        wrapperCol={{
                            span: 24,
                        }}
                        className={styles.loginForm}
                    >
                        <FormItem
                            name="userName"
                            rules={[{ required: true, message: t('login.usernameRules') }]}
                        >
                            <Input id='username' prefix={
                                <UserOutlined style={{ color: '#4e5969' }} />} type="text" placeholder={t('login.userNamePlaceholder')} />
                        </FormItem>
                        <FormItem
                            name="password"
                            rules={[{ required: true, message: t('login.passwordRules') }]}
                        >
                            <Input.Password
                                prefix={
                                    <LockOutlined style={{ color: '#4e5969' }} />
                                }
                                placeholder={t('login.passwordPlaceholder')} />
                        </FormItem>
                        <FormItem noStyle>
                            <Button loading={state?.loading} onClick={onSubmit} type="primary" htmlType="submit" className='custom-btn-primary' style={{ width: '144px', display: 'block', margin: '0 auto', height: '48px', lineHeight: '14px' }}>
                                {t('login.loginBtn')}
                            </Button>
                        </FormItem>
                    </Form>

                    <div className={styles['forget-pwd']} onClick={() => setState(o => ({...o, pwdOpen: true}))}>{t('login.forgetPwd')}</div>
                </div>
            </div>

            <ForgetPwd visible={state.pwdOpen} onClose={() => setState(o => ({...o, pwdOpen: false}))} />
            {contextHolder}
        </div>
    )
}
